import { app, shell, BrowserWindow, session, Menu, globalShortcut, Tray } from 'electron'
import { join, resolve } from 'path'
import { electronApp, optimizer, is } from '@electron-toolkit/utils'
// import pdf from 'pdf-poppler'
import icon from '../../resources/icon.png?asset'
import icon2 from '../../resources/icon@16-16.png?asset'
import exit from '../../resources/exit.png?asset'
import Store from 'electron-store'
import { mkdirSync, existsSync } from 'fs'
import {
  openDirectory,
  getStoreValue,
  setStoreValue,
  deleteStoreValue,
  deleteAllStoreValue,
  setTitle,
  setStoreValues,
  chooseFiles,
  pdfToImg,
  pdfToWord,
  pptToPdf,
  wordToPdf,
  excelToPdf,
  extractResources,
  getFileStreamByPath,
  compress
} from './exportToWebApi'
// import checkUpdate from './update'

// 开发环境下模拟app 升级
Object.defineProperty(app, 'isPackaged', {
  get() {
    return true
  }
})

/**
 * 主窗体
 */
let mainWindow: any = null
async function createWindow(): Promise<void> {
  const store = new Store()
  // Create the browser window.
  mainWindow = new BrowserWindow({
    width: 900,
    height: 670,
    // 最小尺寸
    minWidth: 600,
    minHeight: 400,
    backgroundColor: '#2e2c29',
    show: false,
    // 默认隐藏菜单，用户按一下alt就显示
    // autoHideMenuBar: true,
    // ...(process.platform === 'linux' ? { icon } : {}),
    icon,
    webPreferences: {
      preload: join(__dirname, '../preload/index.js'),
      sandbox: false,
      nodeIntegrationInWorker: true, // 开启worker
      // nodeIntegration: true, // 渲染进程集成node
      contextIsolation: false
      // enableRemoteModule: true
    }
  })
  // eslint-disable-next-line @typescript-eslint/no-var-requires
  // require('@electron/remote/main').initialize()
  // eslint-disable-next-line @typescript-eslint/no-var-requires
  // require('@electron/remote/main').enable(mainWindow.webContents)

  // 子窗体 参数
  const childParam = {
    // parent: BrowserWindow.getFocusedWindow(),
    parent: mainWindow,
    modal: true,
    show: true,
    autoHideMenuBar: true,
    minWidth: 400,
    minHeight: 300,
    icon,
    webPreferences: {
      preload: join(__dirname, '../preload/index.js'),
      sandbox: false,
      // nodeIntegrationInWorker: true, // 开启worker
      // nodeIntegration: true, // 渲染进程集成node
      // contextIsolation: false
      // enableRemoteModule: true
    }
  }

  // 禁止显示默认菜单
  const menuTemplate = [
    {
      label: '输出路径',
      click: () => {
        // mainWindow.webContents.send('open-page', '/outputManage')
        let child: any = new BrowserWindow(childParam)
        if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
          child.loadURL(process.env['ELECTRON_RENDERER_URL'] + '/#' + '/outputManage')
        } else {
          child.loadFile(join(__dirname, '../renderer/index.html'), {
            hash: '/outputManage'
          })
        }
        // child.show()
        // child.on('closed', () => {
        //   child.destroy()
        //   child = null
        //   mainWindow.focus()
        // })
      }
    },
    {
      label: '关于',
      click: () => {
        // mainWindow.webContents.send('open-page', '/about')
        // dialog.showMessageBox({
        //   title: '关于我们',
        //   message: 'pdf转换器',
        //   detail: `${app.getName()} ${app.getVersion()}`
        // })
        let child: any = new BrowserWindow(childParam)
        if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
          child.loadURL(process.env['ELECTRON_RENDERER_URL'] + '/#' + '/about')
        } else {
          child.loadFile(join(__dirname, '../renderer/index.html'), {
            hash: '/about'
          })
        }
        // child.focus()
        // child.on('closed', () => {
        //   child.destroy()
        //   child = null
        //   mainWindow.focus()
        // })
  
      }
    }
  ]
  const menu = Menu.buildFromTemplate(menuTemplate)
  Menu.setApplicationMenu(menu)

  /** 设置窗口标题 */
  setTitle()

  /** 选择文件 */
  chooseFiles()

  /** 选择文件夹 */
  openDirectory()

  /** 获取存储值 */
  getStoreValue(store)

  /** 设置单个存储值 */
  setStoreValue(store)

  /** 设置多个存储值 */
  setStoreValues(store)

  /** 删除存储值 */
  deleteStoreValue(store)

  /** 清空存储值 */
  deleteAllStoreValue(store)

  /** pdf 转图片 */
  pdfToImg(store)

  /** pdf 转word */
  pdfToWord(store)

  /** ppt 转pdf */
  pptToPdf(store)

  /** ppt 转pdf */
  wordToPdf(store)
  /** word 转pdf */
  excelToPdf(store)
  /** 从pdf中提取内容 */
  extractResources(store)
  /** 返回文件流 */
  getFileStreamByPath()
  /** pdf 压缩 */
  compress(store)

  /** 窗口激活时 */
  mainWindow.on('ready-to-show', () => {
    mainWindow.show()
  })

  mainWindow.webContents.setWindowOpenHandler((details) => {
    shell.openExternal(details.url)
    return { action: 'deny' }
  })

  /** 窗口关闭前 */
  mainWindow.on('close', (e) => {
    e.preventDefault()
    // 窗体最小化
    mainWindow.minimize()
  })

  // HMR for renderer base on electron-vite cli.
  // 开发环境和生成环境分别引用不同的html
  // 热更新
  if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
    mainWindow.loadURL(process.env['ELECTRON_RENDERER_URL'])
    // 打开调试工具
    mainWindow.webContents.openDevTools()
    // 添加vue-devtool调试工具
    await session.defaultSession.loadExtension(resolve('./devTools/vue-devtool'))
  } else {
    mainWindow.loadFile(join(__dirname, '../renderer/index.html'))
  }

  globalShortcut.register('Alt+CommandOrControl+Shift+D', () => {
    // 打开调试工具
    mainWindow.webContents.openDevTools()
  })

  // 创建默认文件夹
  try {
    if (existsSync('/pdf文件转换器')) {
      // 文件夹已存在
      const { outputPath } = store.get('outputManage') as any
      if (!outputPath) {
        const pathConfig = {
          outputPath: resolve('/pdf文件转换器'),
          equalSource: false
        }
        store.set('outputManage', pathConfig)
      }
    } else {
      const dir = mkdirSync('/pdf文件转换器')
      console.log('--dir--', dir)
      const pathConfig = {
        outputPath: resolve('/pdf文件转换器'),
        equalSource: false
      }
      store.set('outputManage', pathConfig)
    }
  } catch (error) {
    console.log(error)
  }
  // 检测更新
  // checkUpdate()
}

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
let tray: any = null

// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

// 禁止多开
const gotTheLock = app.requestSingleInstanceLock()
if (!gotTheLock) {
  app.quit()
} else {
  app.on('second-instance', () => {
    // 有人试图运行第二个实例，我们应该关注我们的窗口
    if (mainWindow) {
      if (mainWindow.isMinimized()) mainWindow.restore()
      mainWindow.focus()
    }
  })
  app.on('ready', () => {
    app.whenReady().then(() => {
      // Set app user model id for windows
      electronApp.setAppUserModelId('com.electron')

      // Default open or close DevTools by F12 in development
      // and ignore CommandOrControl + R in production.
      // see https://github.com/alex8088/electron-toolkit/tree/master/packages/utils
      app.on('browser-window-created', (_, window) => {
        optimizer.watchWindowShortcuts(window)
      })

      createWindow()

      // 系统托盘
      tray = new Tray(icon)
      const contextMenu = Menu.buildFromTemplate([
        {
          label: '显示',
          type: 'normal',
          icon: icon2,
          click: () => {
            mainWindow.show()
          }
        },
        {
          label: '退出',
          type: 'normal',
          icon: exit,
          click: () => {
            app.exit()
          }
        }
      ])
      tray.setToolTip('pdf转换器')
      tray.setContextMenu(contextMenu)
      tray.on('click', () => {
        mainWindow.show()
      })

      app.on('activate', function () {
        // On macOS it's common to re-create a window in the app when the
        // dock icon is clicked and there are no other windows open.
        if (BrowserWindow.getAllWindows().length === 0) createWindow()
      })
    })
  })
}
